/*
 * Copyright 2007 www.luzand.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Depends on: ComponentsFactory.js

var yrprxUtil = {};

yrprxUtil.toUtf8 = function (value)
{
    return yrprxComponentsFactory.createScriptableUnicodeConverter().ConvertFromUnicode(value);
}

yrprxUtil.getMimeTypeFromFile = function (file)
{
    return yrprxComponentsFactory.getMIMEService().getTypeFromFile(file);
}

yrprxUtil.getExtension = function (fileName)
{
    try
    {
        var idx = fileName.lastIndexOf('.');

        return idx == -1 ? "" : fileName.substr(idx + 1).toLowerCase();
    }
    catch(ex)
    {
        return "";
    }
}

yrprxUtil.getFileNameWithExtensionFromPath = function (path)
{
    try
    {
        var idx = path.lastIndexOf('/');
        var idx2 = path.lastIndexOf('\\');
        if (idx2 > idx) idx = idx2;

        return idx == -1 ? "" : path.substr(idx + 1);
    }
    catch(ex)
    {
        return "";
    }
}

yrprxUtil.getFileExtension = function (file)
{
    try
    {
        if (!yrprxComponentsFactory.implementsIFile(file))
            return "";

        return yrprxUtil.getExtension(file.leafName);
    }
    catch(ex)
    {
        return "";
    }
}

yrprxUtil.isArray = function (obj)
{
    return obj.constructor.toString().indexOf("function Array()") == 0;
}

yrprxUtil.enumerationToArray = function (enumeration, elemInterface)
{
    var array = new Array;

    while (enumeration.hasMoreElements())
    {
        var elem = enumeration.getNext();
        if (elemInterface) elem = elem.QueryInterface(elemInterface);
        array[array.length] = elem;
    }

    return array;
}

yrprxUtil.trim = function(str)
{
    return str ? str.replace(/^\s+|\s+$/g, '') : null;
}

yrprxUtil.defaultIfEmpty = function(str, def)
{
    try
    {
        return str && str.length > 0 ? str : def;
    }
    catch(ex)
    {
        return def;
    }
}

yrprxUtil.getSpecialFile = function(prop)
{
    return yrprxComponentsFactory.getDirectoryServiceAsProperties().get(prop, Components.interfaces.nsIFile);
}

yrprxUtil.getProfileDirectory = function()
{
    return yrprxUtil.getSpecialFile("ProfD");
}

yrprxUtil.getTempDirectory = function()
{
    return yrprxUtil.getSpecialFile("TmpD");
}

yrprxUtil.getTempDirectoryPath = function()
{
    try
    {
        if (!this._tempDirectoryPath)
            this._tempDirectoryPath = this.getTempDirectory().path;

        return this._tempDirectoryPath;
    }
    catch(ex)
    {
        return "";
    }
}

yrprxUtil.getTempFile = function(fileName)
{
    var tempFile = yrprxUtil.getTempDirectory();

    tempFile.append(fileName);

    return tempFile;
}

yrprxUtil.createTempFileFromOriginalName = function(fileName, ext)
{
    var time = new String(new Date().getTime());
    if (time.length > 7)
        time = time.substring(time.length-7);

    var idx = fileName.lastIndexOf(".");
    if (idx != -1)
    {
        if (!ext) // add current extension
            ext = fileName.substring(idx);
        // get only name
        fileName = fileName.substring(0, idx);
    }

    if (!ext) // add .tmp extension
        ext = ".tmp";

    return this.getTempFile(fileName + time + ext);
}

yrprxUtil.isFile = function(file)
{
    try
    {
        if (!file)
            return false;

        if (!yrprxComponentsFactory.implementsIFile(file))
            return false;

        if (file.isDirectory())
            return false;

        return true;
    }
    catch(ex)
    {
        return false;
    }
}

yrprxUtil.isTempFile = function(file)
{
    try
    {
        if (!yrprxUtil.isFile(file))
            return false;

        return 0 == file.path.indexOf(yrprxUtil.getTempDirectoryPath());
    }
    catch(ex)
    {
        return false;
    }
}

yrprxUtil.isLocalFileURL = function(url)
{
    return url && 0 == url.indexOf("file://");
}

yrprxUtil.getPathByFileURL = function(url)
{
    if (!yrprxUtil.isLocalFileURL(url))
        return url;

    var path = decodeURIComponent(url.substr(7));

    try
    {
        if (yrprxUtil.getOS() == "Windows")
        {
            // remove leading
            if (path[0] == '/') path = path.substr(1);

            // replace to windows format
            while (path.indexOf("/") != -1)
            {
                path = path.replace("/", "\\");
            }
        }
    }
    catch(ex)
    {
        dump(ex);
    }

    return path;
}

yrprxUtil.getBoundedSize = function (realWidth, realHeight, boundWidth, boundHeight)
{
    if (realWidth <= boundWidth && realHeight <= boundHeight)
        return { width : realWidth, height : realHeight };

    return (realWidth > realHeight)
            ? { width : boundWidth, height : Math.floor(boundWidth * realHeight / realWidth) }
            : { width : Math.floor(boundHeight * realWidth / realHeight), height : boundHeight };
}

yrprxUtil.getOS = function ()
{
    if (navigator.appVersion.indexOf("Win")!=-1)
        return "Windows";
    if (navigator.appVersion.indexOf("Mac")!=-1)
        return "MacOS";
    if (navigator.appVersion.indexOf("Linux")!=-1)
        return "Linux";
    if (navigator.appVersion.indexOf("X11")!=-1)
        return "UNIX";

    return "Unknown OS";
}

yrprxUtil.haveNonEnglishCharacters = function (str)
{
    if (!str)
        return false;

    for (var i = 0; i < str.length; ++i)
    {
        if (str.charCodeAt(i) >= 128)
            return true;
    }

    return false;
}

yrprxUtil.encodeToUTF8 = function (str)
{
    var result = "";

    for (var i = 0; i < str.length; ++i)
    {
        var ch = str.charCodeAt(i);

        if (ch < 128)
        {
            result += String.fromCharCode(ch);
        }
        else if ((ch > 127) && (ch < 2048))
        {
            result += String.fromCharCode((ch >> 6) | 192);
            result += String.fromCharCode((ch & 63) | 128);
        }
        else
        {
            result += String.fromCharCode((ch >> 12) | 224);
            result += String.fromCharCode(((ch >> 6) & 63) | 128);
            result += String.fromCharCode((ch & 63) | 128);
        }
    }

    return result;
}

yrprxUtil.decodeFromUTF8 = function (utf8str)
{
    var result = "";

    for (var i = 0; i < utf8str.length; )
    {
        var ch = utf8str.charCodeAt(i++);

        if (ch < 128)
            result += String.fromCharCode(ch);
        else if ((ch > 191) && (ch < 224))
            result += String.fromCharCode(((ch & 31) << 6) | ((utf8str.charCodeAt(i++)) & 63));
        else
            result += String.fromCharCode(((ch & 15) << 12) | (((utf8str.charCodeAt(i++)) & 63) << 6) | ((utf8str.charCodeAt(i++)) & 63));
    }

    return result;
}

yrprxUtil.convertStringToDate = function (dateString)
{
    if (!dateString || !dateString.length)
        return null;

    return new Date(dateString);
}

yrprxUtil.convertStringToTime = function (dateString)
{
    var date = this.convertStringToDate(dateString);

    return date ? date.getTime() : 0;
}

yrprxUtil.convertTimeToString = function (time)
{
    return time ? new Date(time).toString() : null;
}

yrprxUtil.isAppVersionEqualsOrLater = function (value)
{
    try
    {
        var appInfo = yrprxComponentsFactory.getAppInfo();
        var versionChecker = yrprxComponentsFactory.getVersionComparator();

        return versionChecker.compare(appInfo.version, value) >= 0;
    }
    catch(ex)
    {
        dump(ex);
        return false;
    }
}

